<?php

namespace App\Http\Controllers\Home;

use App\models\Bale;
use App\models\Cart;
use App\models\Goods;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CartController extends Controller
{
//    加入购物车的方法
   public function addCart(Goods $goods_id,Bale $bale_id,$num)
   {
//      因为存在重复添加同一货品操作，所以需要先判断添加的货品是否存在，如果存在就更新，不存在就添加
       $cart = Cart::where('user_id',auth()->id())->where('bale_id',$bale_id['id'])->first();
       if ($cart)
       {
           $cart->update(
               [
                 'num' => $cart['num'] + $num,
                 'xiaoji' => ($goods_id['price'] + $bale_id['attach']) * ($cart['num'] + $num),
               ]
           );
       } else {
           Cart::create([
               'goods_id' => $goods_id['id'],
               'bale_id' => $bale_id['id'],
               'num' => $num,
               'user_id' => auth()->id(),
               'xiaoji' => ($goods_id['price'] + $bale_id['attach']) * $num,
           ]) ;
       }
       return back()->with('success','加入购物车成功');
   }

//   加载我的购物车方法
   public function index()
   {
//     获取当前登录用户的购物车数据
       $carts = Cart::where('user_id',auth()->id())->with('goods','bale')->get();
       $goods_id = [];
//       循环当前用户的购物车数据
       foreach ($carts as $k=>$cart)
       {
//           给每个购物车数据加一个checked属性
           $carts[$k]['checked'] = false;
           $carts[$k]['is_collected'] = $cart->goods->collect;

//           $goods_id[] = $cart['goods_id'];
       }
//       dd($carts);
//       该部分给用户推荐已经加入购物车的货品的同一商品分类并且是推荐的商品
       $commendGoods = Goods::where('is_commend',1)->latest()->limit(5)->get();
//       dd($goods);
//       dd($carts);
       return view('home.cart_index',compact('carts','commendGoods'));
   }

   public function delete(Cart $cart)
   {
       $cart->delete();
       return ['valid'=>1,'message'=>'删除成功'];
   }
   public function destory(Cart $cart)
   {
       $cart->delete();
       return back()->with('success','删除成功');
   }

   public function addNum($cart_id,$goods_price,$bale_attach)
   {
//       dd($cart_id);
       $cart = Cart::find($cart_id);
       $bale = $cart->bale;
       if ($cart['num']<$bale['stock']){
           $cart->update(
               [
                   'num' => $cart['num'] + 1,
                   'xiaoji' => $cart['xiaoji'] + $goods_price + $bale_attach,
               ]
           );
       }
       return ['valid'=> 1];
   }
   public function deleteNum($cart_id,$goods_price,$bale_attach)
   {
       $cart = Cart::find($cart_id);
       if ($cart['num']>1){
           $cart->update(
               [
                   'num' => $cart['num'] - 1,
                   'xiaoji' => $cart['xiaoji'] - $goods_price - $bale_attach,
               ]
           );
       }
       return ['valid'=> 1];
   }
}
